<template>
  <div v-loading="loadingData">
    <div style="margin-bottom: 10px;display: flex;align-items: center;">
      报工时间：
      <el-date-picker
        v-model="reportTime"
        type="datetime"
        format="YYYY-MM-DD HH:mm:ss"
        value-format="YYYY-MM-DD HH:mm:ss"
        placeholder="请选择报工时间"
        :clearable="false"
        style="width: 240px !important;margin-right: 20px;height: 35px;"
      />
      <el-button type="primary" @click="batchAddToTableB">添加报工</el-button>
    </div>
    <el-table
      ref="tableA"
      :data="tableData"
      class="table v-table process-table"
      style="width: 100%"
      :default-sort="{ prop: defaultSort, order: 'descending' }"
      highlight-current-row
      border
      :row-style="rowStyle"
      @selection-change="tableSelectionChange"
    >
      <!-- 无数据 -->
      <template slot="empty">
        <p>暂无数据</p>
      </template>
      <!-- 序号列 -->
      <el-table-column label="序号" type="index" width="50" />
      <!-- 选择列 -->
      <el-table-column type="selection" width="50" />
      <el-table-column
        v-for="(item, index) in tableKey"
        :id="'table' + item.value + index"
        :key="'table' + item.value + index"
        :prop="item.value"
        :label="item.name"
        :min-width="item.minWidth"
        :align="item.algin || 'left'"
        :sortable="(item.sortable && 'custom') || false"
        show-overflow-tooltip
        :sort-orders="
          item.value === defaultSort
            ? ['ascending', 'descending']
            : ['ascending', 'descending', null]
        "
      >
        <template v-if="!item.slot" #default="scope">
          <span>{{ formatterCellVal(scope.row[item.value]) }}</span>
        </template>
        <template v-else #default="scope">
          <!-- <span v-if="item.value === 'status'">
            <span v-if="scope.row.status === 1" type="success">未开始</span>
            <span v-if="scope.row.status === 2" type="warning">进行中</span>
            <span v-if="scope.row.status === 3" type="danger">已完成</span>
            <span v-if="scope.row.status === 4" type="danger">已撤回</span>
            <span v-if="scope.row.status === 5" type="danger">已取消</span>
          </span> -->
        </template>
      </el-table-column>
    </el-table>
    <el-divider style="margin: 20px 0"></el-divider>
    <el-form
      :inline="true"
      ref="formsTableRef"
      :model="addReportWorkBatchList"
      label-width="126px"
      class="demo-form-inline"
    >
      <el-table
        border
        :data="addReportWorkBatchList"
        ref="inspectionTableRef"
        class="table v-table"
        style="width: 100%; overflow-y: auto;"
      >
        <!-- 序号列 -->
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column label="工单" min-width="250">
          <template #default="scope">
            <el-form-item
              :prop="scope.$index + `.workOrderCode`"
              class="not-need-form"
            >
              <el-input
                v-model.trim="
                  addReportWorkBatchList[scope.$index].workOrderCode
                "
                style="width: 100%"
                disabled
              />
            </el-form-item>
          </template>
        </el-table-column>
        <!-- 工序名称 -->
        <el-table-column label="工序名称" min-width="180">
          <template #default="scope">
            <el-form-item
              :prop="scope.$index + `.process_Id`"
              class="not-need-form"
              :rules="{
                required: true,
                message: '工序名称不能为空',
                trigger: ['change', 'blur'],
              }"
            >
              <el-select
                v-model="addReportWorkBatchList[scope.$index].process_Id"
                placeholder="请选择工序名称"
                style="width: 100%"
                disabled
              >
                <el-option
                  v-for="emp in addReportWorkBatchList[scope.$index].processNameOption"
                  :key="emp.process_Id"
                  :label="emp.processName"
                  :value="emp.process_Id"
                  @click="handleProcessSelectChange(emp, scope.$index)"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <!-- 班组名称 -->
        <el-table-column label="班组名称" min-width="180">
          <template #default="scope">
            <el-form-item
              :prop="scope.$index + `.teamId`"
              class="not-need-form"
              :rules="{
                required: true,
                message: '班组不能为空',
                trigger: ['change', 'blur'],
              }"
            >
              <el-select
                v-model="addReportWorkBatchList[scope.$index].teamId"
                placeholder="请选择班组"
                style="width: 100%"
              >
                <el-option
                  v-for="emp in teamOptions"
                  :key="emp.teamId"
                  :label="emp.teamName"
                  :value="emp.teamId"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <!-- 设备名称 -->
        <el-table-column label="设备名称" min-width="200">
          <template #default="scope">
            <el-form-item
              :prop="scope.$index + `.vendId`"
              class="not-need-form"
              :rules="{
                required: true,
                message: '设备不能为空',
                trigger: ['change', 'blur'],
              }"
            >
              <el-select
                v-model="addReportWorkBatchList[scope.$index].vendId"
                placeholder="请选择设备"
                style="width: 100%"
              >
                <el-option
                  v-for="emp in equipmentOptions"
                  :key="emp.vendId"
                  :label="emp.vendName"
                  :value="emp.vendId"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <!-- 报工可用数 -->
        <el-table-column label="报工可用数" min-width="200">
          <template #default="scope">
            <el-form-item
              :prop="scope.$index + `.reportAvailableQuantity`"
              class="not-need-form"
            >
              <el-input
                v-model.trim="
                  addReportWorkBatchList[scope.$index].reportAvailableQuantity
                "
                style="width: 100%"
                disabled
              />
            </el-form-item>
          </template>
        </el-table-column>
        <!-- 报工数 -->
        <el-table-column label="报工数" min-width="200">
          <template #default="scope">
            <el-form-item
              :prop="scope.$index + `.reportQty`"
              class="not-need-form"
              :rules="[{
                required: true,
                message: '报工数不能为空',
                trigger: ['blur'],
              },{
                validator: (rule, value, callback) => validateQty(rule, value, callback,addReportWorkBatchList[scope.$index].workOrder_Id, scope.$index,'报工数'),
                trigger: ['blur'],
              }]"
            >
              <el-input-number
                v-model.trim="addReportWorkBatchList[scope.$index].reportQty"
                :min="0"
                :max="addReportWorkBatchList[scope.$index].reportAvailableQuantity"
                :precision="2"
                placeholder="请输入报工数"
                @input="(v) => handleInput(v, 'reportQty', scope.$index)"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <!-- 生产人员 -->
        <el-table-column label="生产人员" min-width="180">
          <template #default="scope">
            <el-form-item
              :prop="scope.$index + `.inspectionId`"
              class="not-need-form"
              :rules="{
                required: true,
                message: '生产人员不能为空',
                trigger: ['change', 'blur'],
              }"
            >
              <el-select
                v-model="addReportWorkBatchList[scope.$index].inspectionId"
                placeholder="请选择生产人员"
                style="width: 100%"
              >
                <el-option
                  v-for="emp in employeeOption"
                  :key="emp.id"
                  :label="emp.employeesName"
                  :value="emp.id"
                />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <!-- 良品数 -->
        <el-table-column label="良品数" min-width="200">
          <template #default="scope">
            <el-form-item
              :prop="scope.$index + `.goodQty`"
              class="not-need-form"
              :rules="[{
                required: true,
                message: '良品数不能为空',
                trigger: ['blur'],
              },{
                validator: (rule, value, callback) => validateQty(rule, value, callback,addReportWorkBatchList[scope.$index].workOrder_Id, scope.$index,'良品数'),
                trigger: ['blur'],
              }]"
            >
             <el-input-number
                v-model.trim="addReportWorkBatchList[scope.$index].goodQty"
                :min="0"
                :precision="2"
                :max="addReportWorkBatchList[scope.$index].reportAvailableQuantity"
                :disabled="!addReportWorkBatchList[scope.$index].reportQty"
                placeholder="请输入良品数"
                @input="(v) => handleInput(v, 'goodQty', scope.$index)"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <!-- 不良品数 -->
        <el-table-column label="不良品数" min-width="210">
          <template #default="scope">
            <el-form-item
              :prop="scope.$index + `.noGoodQty`"
              class="not-need-form"
              :rules="[{
                required: true,
                message: '不良品数不能为空',
                trigger: ['blur'],
              },{
                validator: (rule, value, callback) => validateQty(rule, value, callback,addReportWorkBatchList[scope.$index].workOrder_Id, scope.$index,'不良品数'),
                trigger: ['blur'],
              }]"
            >
              <el-input-number
                v-model.trim="addReportWorkBatchList[scope.$index].noGoodQty"
                :min="0"
                :precision="2"
                :max="addReportWorkBatchList[scope.$index].reportAvailableQuantity"
                :disabled="!addReportWorkBatchList[scope.$index].reportQty"
                placeholder="请输入不良品数"
                @input="(v) => handleInput(v, 'noGoodQty', scope.$index)"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <!-- 不良品项 -->
        <el-table-column label="不良品项" min-width="200">
          <template #default="scope">
            <el-form-item
              :prop="scope.$index + `.defectItemId`"
              class="not-need-form"
              :rules="{
                required: addReportWorkBatchList[scope.$index].noGoodQty,
                message: '不良品项不能为空',
                trigger: ['change', 'blur'],
              }"
            >
              <el-select v-model="addReportWorkBatchList[scope.$index].defectItemId" clearable collapse-tags-tooltip
                :placeholder="addReportWorkBatchList[scope.$index].noGoodQty?'请选择不良品项':' '" :disabled="!addReportWorkBatchList[scope.$index].noGoodQty">
                <el-option v-for="emp in defectItemOption" :key="emp.defectItem_Id"
                    :label="emp.defectItemName" :value="emp.defectItem_Id" />
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>
        <!-- 开始时间 -->
        <el-table-column label="开始时间" min-width="250">
          <template #default="scope">
            <div style="display: flex;">
              <el-form-item
                :prop="scope.$index + `.startDateDay`"
                class="not-need-form"
                style="margin-right: 10px !important;"
                :rules="[{
                  required: true,
                  message: '日期不能为空',
                  trigger: ['change','blur'],
                }]"
              >
                <el-date-picker
                  v-model="addReportWorkBatchList[scope.$index].startDateDay"
                  type="date"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择日期"
                  style="width: 120px !important;"
                  :clearable="false"
                  @change="handleTimeChange(scope.$index, 'start')"
                />
              </el-form-item>
              <el-form-item
                :prop="scope.$index + `.startDateTime`"
                class="not-need-form"
                :rules="[{
                  required: true,
                  message: '时间不能为空',
                  trigger: ['blur'],
                },{
                  validator: validateTime,
                  trigger: ['blur'],
                }]"
              >
                <el-input
                  v-model="addReportWorkBatchList[scope.$index].startDateTime"
                  style="width: 100px;"
                  placeholder="HH:mm"
                  @blur="handleTimeChange(scope.$index, 'start', 'time')"
                  @input="handleTimeChange(scope.$index, 'start', 'time')"
                >
                </el-input>
              </el-form-item>
            </div>
          </template>
        </el-table-column>
        <!-- 结束时间 -->
        <el-table-column label="结束时间" min-width="250">
          <template #default="scope">
            <div style="display: flex;">
              <el-form-item
                :prop="scope.$index + `.endDateDay`"
                class="not-need-form"
                style="margin-right: 10px !important;"
                :rules="[{
                  required: true,
                  message: '日期不能为空',
                  trigger: ['change','blur'],
                }]"
              >
                <el-date-picker
                  v-model="addReportWorkBatchList[scope.$index].endDateDay"
                  type="date"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择日期"
                  style="width: 120px !important;"
                  :clearable="false"
                  @change="handleTimeChange(scope.$index, 'end')"
                />
              </el-form-item>
              <el-form-item
                :prop="scope.$index + `.endDateTime`"
                class="not-need-form"
                :rules="[{
                  required: true,
                  message: '时间不能为空',
                  trigger: ['blur'],
                },{
                  validator: validateTime,
                  trigger: ['blur'],
                }]"
              >
                <el-input
                  v-model="addReportWorkBatchList[scope.$index].endDateTime"
                  style="width: 100px;"
                  placeholder="HH:mm"
                  @blur="handleTimeChange(scope.$index, 'end', 'time')"
                  @input="handleTimeChange(scope.$index, 'end', 'time')"
                >
                </el-input>
              </el-form-item>
            </div>
          </template>
        </el-table-column>
        <!-- 报工时长（小时） -->
        <el-table-column label="报工时长（小时）" min-width="140">
          <template #default="scope">
            <el-form-item
              :prop="scope.$index + `.reoportDurationHour`"
              class="not-need-form"
            >
             <el-input
                v-model.trim="addReportWorkBatchList[scope.$index].reoportDurationHour"
                disabled
              />
            </el-form-item>
          </template>
        </el-table-column>
        <!-- 报工时长（分钟） -->
        <el-table-column label="报工时长（分钟）" min-width="140">
          <template #default="scope">
            <el-form-item
              :prop="scope.$index + `.reoportDurationMinute`"
              class="not-need-form"
            >
              <el-input
                v-model.trim="addReportWorkBatchList[scope.$index].reoportDurationMinute"
                disabled
              />
            </el-form-item>
          </template>
        </el-table-column>
        <!-- 存货名称 -->
        <el-table-column label="存货名称" min-width="200">
          <template #default="scope">
            <el-form-item
              :prop="scope.$index + `.inventoryName`"
              class="not-need-form">
              <el-input
                v-model.trim="addReportWorkBatchList[scope.$index].inventoryName"
                disabled
                placeholder="请输入存货名称"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <!-- 存货编码 -->
        <el-table-column label="存货编号" min-width="200">
          <template #default="scope">
            <el-form-item
              :prop="scope.$index + `.inventoryCode`"
              class="not-need-form">
              <el-input
                v-model.trim="addReportWorkBatchList[scope.$index].inventoryCode"
                disabled
                placeholder="请输入存货编号"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <!-- 产品规格 -->
        <el-table-column label="产品规格" min-width="200">
          <template #default="scope">
            <el-form-item
              :prop="scope.$index + `.specificationModel`"
              class="not-need-form">
              <el-input
                v-model.trim="addReportWorkBatchList[scope.$index].specificationModel"
                disabled
              />
            </el-form-item>
          </template>
        </el-table-column>
        <!-- 单位 -->
        <el-table-column label="单位" min-width="200">
          <template #default="scope">
            <el-form-item
              :prop="scope.$index + `.unitName`"
              class="not-need-form">
              <el-input
                v-model.trim="addReportWorkBatchList[scope.$index].unitName"
                disabled
                placeholder="请输入单位"
              />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="60" fixed="right">
          <template #default="scope">
            <el-button
              @click="
                handleDeleteRow(addReportWorkBatchList[scope.$index])
              "
              type="text"
              style="color: #f54346"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-form>
  </div>
</template>

<script>
import { calculateWorkTime } from "@/uitils/publicMethod.js"
export default {
  props: {},
  components: {},
  data() {
    return {
      loadingData: false,
      reportTime: '',
      tableKey: [
        { value: "workOrderCode", name: "工单编号", minWidth: "200" },
        { value: "inventoryCode", name: "存货编号", minWidth: "160" },
        { value: "inventoryName", name: "存货名称", minWidth: "150" },
        { value: "specificationModel", name: "产品规格", minWidth: "140" },
        { value: "unitName", name: "单位", minWidth: "150" },
        { value: "planQty", name: "计划数", minWidth: "120" },
        { value: "planStartDate", name: "计划开始时间", minWidth: "160" },
        { value: "planEndDate", name: "计划结束时间", minWidth: "160" },
        { value: "actualStartDate", name: "实际开始时间", minWidth: "160" },
        { value: "actualEndDate", name: "实际结束时间", minWidth: "160" },
        { value: "remark", name: "备注", minWidth: "200" },
      ],
      tableData: [],
      tableSelectionExist: [],
      tableSelection: [],
      addReportWorkBatchList: [],
      employeeOption: [],
      defectItemOption: [],
      teamOptions: [],
      equipmentOptions: []
    };
  },
  watch: {
    reportTime: function (newVal, oldVal) {
      if(newVal) {
        // 这里可以执行一些操作，比如更新DOM或发送请求等
        console.log('Time changed:', newVal);
        const timeObj = this.convertTime(newVal)
        this.addReportWorkBatchList = this.addReportWorkBatchList.map(item=>{
          return {
            ...item,
            startDateDay: timeObj.startDate.day,
            startDateTime: timeObj.startDate.time,
            endDateDay: timeObj.endDate.day,
            endDateTime: timeObj.endDate.time,
            reoportDurationHour: timeObj.reoportDurationObj.hours || 0,
            reoportDurationMinute: timeObj.reoportDurationObj.minutes || 0
          }
        })
      }
    },
  },
  created() {},
  mounted() {},
  methods: {
    calculateWorkTime,
    rowStyle({ row, rowIndex }) {
      if (rowIndex % 2 === 0) {
        // 偶数行
        return {};
      } else {
        return { backgroundColor: "#f9f9f9" };
      }
    },
    // 无内容显示占位符
    formatterCellVal(cellValue) {
      return !cellValue && cellValue !== 0 ? "--" : cellValue;
    },
    tableSelectionChange(val) {
      this.tableSelection = [ ...val ];
    },
    // 添加到表格B
    batchAddToTableB() {
      // 必须添加报工时间
      if(!this.reportTime){
        this.$message.warning("请先选择报工时间");
        return
      }
      // 如果tableSelectionCopy>0 则表示已经有数据被添加到子表了
      if (this.tableSelection.length === 0 && this.tableSelectionExist.length === 0) {
        this.$message.warning("请先选择要添加的数据");
        return;
      }
      // 找差异 需要取消的
      // 将 B 数组转换为字符串集合
      const bSet = new Set(this.tableSelection.map(item => JSON.stringify(item)));
      // 找不存在的数据
      const notExisting = this.tableSelectionExist.filter(item => !bSet.has(JSON.stringify(item)));
      if(notExisting.length > 0) {
        notExisting.forEach((item) => {
          this.addReportWorkBatchList = this.addReportWorkBatchList.filter(item2 => item2.workOrder_Id !== item.workOrder_Id);
        });
      }
      this.tableSelection.forEach((row) => {
        this.addToTableB(row);
      });
      this.tableSelectionExist = [ ...this.tableSelection ]
      console.log('选中数据:',this.tableSelectionExist);
    },
    // 获取工序详情
    // getProcessDetailInfo(row) {
    //   const url = `api/Production_ReportWorkOrder/GetProcessInfoByWorkOrderId/${row.workOrder_Id}`;
    //   return this.http
    //     .get(url, {}, true)
    //     .then((res) => (res.status === 0 ? res.rows : false));
    // },
    // 获取工序名称
    async getProcessInfoList(row) {
      const url = `api/Production_ReportWorkOrder/GetProcessInfoByWorkOrderId/${row.workOrder_Id}`;
      return this.http
        .post(url, {}, true)
        .then((res) => (res.ok ? res.data : false));
    },
    // 转换时间
    convertTime(timeStr) {
      // 创建 Date 对象
      const date = new Date(timeStr);
      date.setHours(date.getHours() + 8);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = date.getSeconds().toString().padStart(2, "0");
      const startDateDay = timeStr.split(' ')[0]
      const startDateTime = timeStr.split(' ')[1].split(':')[0]+':'+timeStr.split(' ')[1].split(':')[1]
      const endDateDay = year + '-' + month + '-' + day
      const endDateTime = hours + ':' + minutes
      // 获取时长 小时 分钟 必须传为YYYY-MM-DD HH:mm:ss 或 YYYY-MM-DD HH:mm格式
      const reoportDurationObj = this.calculateWorkTime(timeStr, endDateDay+' '+endDateTime+':'+seconds)
      return {
        startDate: {
          day: startDateDay,
          time: startDateTime
        },
        endDate: {
          day: endDateDay,
          time: endDateTime
        },
        reoportDurationObj: {
          hours: reoportDurationObj.hours,
          minutes: reoportDurationObj.minutes
        }
      }
    },
    // 添加数据到表格B
    async addToTableB(row) {
      // 检查是否已经存在
      const exists = this.addReportWorkBatchList.some((item) => item.workOrder_Id === row.workOrder_Id);
      if (!exists) {
        this.loadingData = true;
        try {
          const [data1] = await Promise.all([
            this.getProcessInfoList(row),
          ]);
          if (data1) {
            const timeObj = this.convertTime(this.reportTime)
            data1.forEach((item,index) => {

              let reportAvailableQuantity = item.reportAvailableQuantity || 0;

              // 如果不是第一行，需要累加上一行的goodQty值
              if (index > 0) {
                // 查找同一工单下上一行的数据
                const previousItems = this.addReportWorkBatchList.filter(
                  existingItem => existingItem.workOrder_Id === row.workOrder_Id
                );

                // 如果已经存在上一行的数据，则累加
                if (previousItems.length > 0 && previousItems[index - 1]) {
                  reportAvailableQuantity += previousItems[index - 1].goodQty;
                }
              }

              this.addReportWorkBatchList.push({
                timeId: Date.now() + Math.random().toString(36).substr(2, 9),
                workOrder_Id: row.workOrder_Id, // 工单编号
                workOrderCode: row.workOrderCode,
                process_Id: item.process_Id,// 工序名称
                inventory_Id: row.inventory_Id, // 存货id
                inventoryName: row.inventoryName, // 存货名称
                specificationModel: row.specificationModel, // 产品规格
                inventoryCode: row.inventoryCode, // 存货编码
                unitName: row.unitName, // 单位
                planQty: row.planQty, // 计划数
                inspectionId: null, // 生产人员
                reportAvailableQuantity: reportAvailableQuantity, // 报工可用数
                reportAvailableQuantityCopy: item.reportAvailableQuantity, // 报工可用数
                reportQty: reportAvailableQuantity, // 报工数
                goodQty: reportAvailableQuantity, // 良品数
                noGoodQty: 0, // 不良品数
                defectItemId: null, // 不良品项
                startDate: '', // 开始时间
                endDate: '', // 结束时间
                startDateDay: timeObj.startDate.day,
                startDateTime: timeObj.startDate.time,
                endDateDay: timeObj.endDate.day,
                endDateTime: timeObj.endDate.time,
                reoportDurationHour: timeObj.reoportDurationObj.hours || 0,  // 报工时长
                reoportDurationMinute: timeObj.reoportDurationObj.minutes || 0, // 报工时长
                processNameOption: data1,
                sort: item.sort,
                vendId: null, // 设备id
                teamId: null,  // 班组id
              });
            });
          }
          this.loadingData = false;
        } catch (error) {
          this.loadingData = false;
          console.error("获取数据失败:", error);
        }
        this.$message.success(`已添加 ${row.workOrderCode} 到表格`);
      } else {
        // this.$message.warning(`${row.workOrderCode} 已在表格中`);
      }
    },

    // 删除行数据 删除数据同步取消工序的选中状态
    handleDeleteRow(row) {
      let data = this.addReportWorkBatchList;
      for (var i = 0; i < data.length; i++) {
        if (data[i].timeId == row.timeId) {
          data.splice(i, 1);
        }
      }
      // 如果删除的addReportWorkBatchList数据中 没有workOrder_Id行数据了
      // 则需要取消工单的选中状态
      console.log(data,row,data.filter(item => item.workOrder_Id === row.workOrder_Id));
      const isExit = data.filter(item => item.workOrder_Id === row.workOrder_Id) && data.filter(item => item.workOrder_Id === row.workOrder_Id).length > 0
      if(!isExit){
        const closeStatusTableRow = this.tableData.find(item=>item.workOrder_Id===row.workOrder_Id)
        this.deleteDeselect(closeStatusTableRow)
      }
    },
    // 删除数据同步取消工序的选中状态
    deleteDeselect(row) {
      this.$nextTick(() => {
        if (row) {
          this.$refs.tableA.toggleRowSelection(row, false);
        }
      });
    },
    handleInput(val, type, index) {
      console.log(val, type, index);
      if (val === null && val != 0) return;
      // 处理数据
      // 报工数
      if(type==='reportQty') {
        // 默认良品数等于报工数
        this.addReportWorkBatchList[index].goodQty = this.addReportWorkBatchList[index][type];
        this.addReportWorkBatchList[index].noGoodQty = 0;
      }
      // 良品数
      if(type==='goodQty') {
        this.addReportWorkBatchList[index].noGoodQty = this.addReportWorkBatchList[index].reportQty - this.addReportWorkBatchList[index][type];
      }
      // 不良品数
      if(type==='noGoodQty') {
        this.addReportWorkBatchList[index].goodQty = this.addReportWorkBatchList[index].reportQty - this.addReportWorkBatchList[index][type];
      }
      const arr = [ ...this.addReportWorkBatchList ]
      const someProcessDataList = arr.slice(index+1, arr.length).filter(item=>item.workOrder_Id===arr[index].workOrder_Id).map(i=>i.timeId)
      // someProcessDataList有值表示更改的不是同一个工单的最后一条，不是最后一条需要将当前行后面的数据重新计算，反之最后一条不需要
      // 报工可用数=当前行报工可用数+上一行良品数
      if(someProcessDataList.length > 0){
        this.addReportWorkBatchList.forEach((item, index)=>{
          if(someProcessDataList.includes(item.timeId)){
            item.reportAvailableQuantity = item.reportAvailableQuantityCopy + this.addReportWorkBatchList[index-1].goodQty
            item.reportQty = item.reportAvailableQuantity
            item.goodQty = item.reportAvailableQuantity
            item.noGoodQty = 0
          }
        })
      }
    },
    resetForm() {
      this.reportTime = '';
      this.$nextTick(() => {
        this.addReportWorkBatchList = [];
        this.tableData = []
        this.tableSelectionExist = []
        this.tableSelection = []
        this.employeeOption = []
        this.defectItemOption = []
        this.teamOptions = []
        this.equipmentOptions = []
        this.$refs.formsTableRef && this.$refs.formsTableRef.clearValidate();
      });
    },
    handleProcessSelectChange(value, index) {
      this.addReportWorkBatchList[index].sort = value.sort
    },
    // 校验时间
    validateTime(rule, value, callback) {
      if (!value) {
        return callback(new Error('时间不能为空'));
      }
      // 正则表达式校验 HH:mm 格式
      const timeRegex = /^([01]?[0-9]|2[0-3]):([0-5][0-9])$/;
      if (!timeRegex.test(value)) {
        return callback(new Error('时间格式不正确，请使用 HH:mm 格式'));
      }
      callback();
    },
    // 校验开始时间和结束时间关系，并计算时长
    validateTimeRange(index, type) {
      const row = this.addReportWorkBatchList[index];
      // 检查必要字段是否填写
      if (!row.startDateDay || !row.startDateTime || !row.endDateDay || !row.endDateTime) {
        // this.clearDuration(index);
        // return { isValid: false, error: '请填写完整的开始时间和结束时间' };
        return
      }
      try {
        const startTimeStr = `${row.startDateDay} ${row.startDateTime}`;
        const endTimeStr = `${row.endDateDay} ${row.endDateTime}`;
        // 解析时间
        const startTime = this.parseTimeString(startTimeStr);
        const endTime = this.parseTimeString(endTimeStr);
        // 验证时间关系
        if (startTime >= endTime) {
          this.clearDuration(index);
          return {
            isValid: false,
            error: type === 'start' ? '开始时间不能晚于或等于结束时间' : '结束时间不能早于或等于开始时间'
          };
        }
        // 计算时长并更新
        this.calculateAndUpdateDuration(startTime, endTime, index);
        return { isValid: true, error: null };
      } catch (error) {
        this.clearDuration(index);
        return { isValid: false, error: error.message };
      }
    },
    // 解析时间字符串
    parseTimeString(timeStr) {
      const regex = /^(\d{4})-(\d{1,2})-(\d{1,2})[\sT](\d{1,2}):(\d{1,2})$/;
      const match = timeStr.match(regex);

      if (!match) {
        throw new Error("时间格式错误");
      }

      const [_, year, month, day, hour, minute] = match;

      const date = new Date(
        parseInt(year),
        parseInt(month) - 1,
        parseInt(day),
        parseInt(hour),
        parseInt(minute)
      );

      if (isNaN(date.getTime())) {
        throw new Error("无效的日期时间");
      }

      return date;
    },
    // 计算并更新时长
    calculateAndUpdateDuration(startTime, endTime, index) {
      const timeDiff = endTime - startTime;
      const totalMinutes = Math.floor(timeDiff / (1000 * 60));
      const hours = Math.floor(totalMinutes / 60);
      const minutes = totalMinutes % 60;
      // 更新时长显示
      this.addReportWorkBatchList[index].reoportDurationHour = hours;
      this.addReportWorkBatchList[index].reoportDurationMinute = minutes;
    },
    // 清空时长
    clearDuration(index) {
      this.addReportWorkBatchList[index].reoportDurationHour = '';
      this.addReportWorkBatchList[index].reoportDurationMinute = '';
    },
    // 实时校验（在输入变化时调用）
    handleTimeChange(index, type, time='day') {
      // 防抖处理，避免频繁计算
      clearTimeout(this.validateTimer);
      this.validateTimer = setTimeout(() => {
        const result = this.validateTimeRange(index, type);
        if (!result.isValid) {
          // 显示错误提示
          this.$message.error(`第${index + 1}行: ${result.error}`);
          if(time==='day') {
            // 清空
            this.addReportWorkBatchList[index][type === 'start'?'startDateDay':'endDateDay'] = ''
          }
        }
      }, 500);
    },
    // 检验报工数 良品数 不良品数
    validateQty(rule, value, callback, workOrderId, index,text) {
      if (!value&&value!=0) {
        return callback(new Error(text+'不能为空'));
      }
      /*校验规则：
        报工数：第一条 ≤ 报工可用数，后续条 ≤（当前行的报工可用数 +上一条的良品数）
        良品数规则：第一条 ≤ 报工数，后续条 ≤ （当前行的报工可用数 +上一条的良品数）
        不良品数规则：第一条 ≤ 报工数，后续条 ≤ （当前行的报工可用数 +上一条的良品数）
      */
      if(index!=0) {
        const arr = [ ...this.addReportWorkBatchList ]
        const someProcessDataList = arr.slice(0, index).filter(item=>item.workOrder_Id===workOrderId)
        // 能查到同一条工单的信息 表示之前有填写数据
        if(someProcessDataList && someProcessDataList.length > 0) {
          // 不能超过当前行的报工可用数
          const upReportAvailableQuantity = arr[index].reportAvailableQuantity
          if(value > upReportAvailableQuantity) {
            return callback(new Error(text+'不正确'));
          }
        }
      }
      callback();
    },
    confirmChange() {
      if (this.addReportWorkBatchList.length === 0) {
        return this.$message.error("至少添加一行工序数据");
      }
      this.$refs.formsTableRef.validate(async (valid) => {
        if (valid) {
          this.$emit("pass-verification-change");
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.process-table {
  max-height: 300px;
  overflow-y: auto;
}
.add-process-btn {
  margin-bottom: 10px;
}
::v-deep {
  .not-need-form {
    .el-form-item__content {
      margin-left: 0 !important;
    }
  }
  .el-date-editor.el-input,
  .el-date-editor.el-input__wrapper,
  .el-input-number {
    width: 100% !important;
  }
  .el-form-item--default .el-form-item__label {
    height: 32px;
    line-height: 20px !important;
    align-items: center !important;
    text-align: right;
  }
  .el-space {
    width: 100% !important;
  }
  .el-space__item {
    margin-right: 0 !important;
    width: 100% !important;
  }
}
.el-form--inline .el-form-item {
  width: 100% !important;
}
.not-need-form.el-form-item--default {
  margin-bottom: 13px !important;
  margin-top: 13px !important;
}
</style>
